#!/usr/bin/python
# -*- coding: UTF-8 -*-

################################################################################
#
# Copyright (c) 2020 openEuler.org, Inc. All Rights Reserved
#
################################################################################
"""
Clear historical files regularly

Authors: xiaojianghui
Date:    10/22/2020 11:01 AM
"""

import datetime
import os
import time


def deldir(dirx):
    """
    Delete files older than one month
    :param dirx:dir struct
    """
    files = os.listdir(dirx)
    for filex in files:
        file_path = dirx + "/" + filex
        if os.path.isfile(file_path):
            # Last modified time
            # Get file timestamp
            last1 = os.stat(file_path).st_mtime
            filetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(last1))
            # Get expiration time
            starttime = datetime.datetime.now()
            d1 = starttime + datetime.timedelta(days=-30)
            date1 = str(d1)
            index = date1.find(".")
            datatime01 = date1[:index]
            # datatime01 is the time 7 days before the current time, filetime is the time of file modification,
            # if the file time is less than (earlier) datatime01 time, delete fileu
            if datatime01 > filetime:
                os.remove(file_path)
                print(file_path + "was removed!")
        elif os.path.isdir(file_path):
            # If it is a folder, continue to traverse
            deldir(file_path)
            # Delete if the folder is empty
            if not os.listdir(file_path):
                os.rmdir(file_path)
                print("empty folder" + file_path + "was removed!")
